﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Agile.Service.Rbac;
using Microsoft.AspNetCore.Mvc;

namespace Web.Areas.Rbac.Controllers {
    [Area("rbac")]
    public class MenuController:BaseController<Menu> {
        private readonly IMenuService _menuService;
        private readonly IMenuElementService _menuElementService;
        private static string baseUrl = "http://localhost:85";
        public MenuController(IMenuService menuService,IMenuElementService menuElementService) {
            _menuService = menuService;
            _menuElementService = menuElementService;
            baseUrl = new StringBuilder().Append(Request?.Scheme).Append("://").Append(Request?.Host).ToString();
        }
        [HttpGet]
        public IActionResult GetTreeSelectJson() {
            var data = _menuService.FindAll().OrderByDescending(p => p.OrderBy).ToList();
            var treeList = new List<TreeSelectModel>();
            foreach(Menu item in data) {
                TreeSelectModel treeModel = new TreeSelectModel();
                treeModel.id = item.ID;
                treeModel.text = item.Name;
                treeModel.parentId = item.ParentID;
                treeModel.data = item;
                treeList.Add(treeModel);
            }
            return Content(treeList.TreeSelectJson());
        }
        [HttpGet]
        public IActionResult GetGridDataJson(string pId,Paging paging) {
            System.Text.StringBuilder strWhere = new System.Text.StringBuilder();
            strWhere.Append(" 1=1 ");
            if(!string.IsNullOrWhiteSpace(pId)) {
                strWhere.Append(" AND (ParentID='" + pId + "' OR ID='" + pId + "') ");
            }
            if(!string.IsNullOrWhiteSpace(paging.keyword)) {
                strWhere.Append(" AND Name like '%" + paging.keyword + "%' ");
            }
            paging.sqlwhere = strWhere.ToString();
            return base.GetJGridPageDataJson(paging);
        }
        [HttpPost]
        public IActionResult Collect() {
            string baseUrl = "";
            var menus = _menuService.FindAll("Name NOT IN('系统结构','健康检查','图标管理') AND ParentID<>'00000000-0000-0000-0000-000000000000'");
            foreach(var menu in menus) {
                var uri = menu.Url.Split("/");
                if(uri.Length <= 1) continue;
                string url = baseUrl + menu.Url;
                string testContent = GetPageContent(url);
                if(!string.IsNullOrWhiteSpace(testContent)) {
                    string pattern = @"<a\b[^>]+\bid=""NF-([^""]*)""[^>]*>([\s\S]*?)</a>";
                    Regex s = new Regex(pattern);
                    if(s.IsMatch(testContent)) {
                        foreach(Match item in s.Matches(testContent)) {
                            //<a id="NF-add" authorize="yes" class="btn btn-primary dropdown-text" onclick="AddBatch()"><i class="glyphicon glyphicon-plus"></i>新增</a>
                            string tempstr = item.Groups[0].Value;
                            MenuElement pageButton = new MenuElement();
                            pageButton.ModuleId = menu.ID;
                            pageButton.Name = Utils.GetChineseWord(tempstr);
                            pageButton.DomId = GetBtnInfo(tempstr,@"id=.+?""","id=");
                            pageButton.Icon = GetBtnInfo(tempstr,@"<i\b[^>]+\bclass=.+?""","<i").Replace("class=","");
                            pageButton.Script = GetBtnInfo(tempstr,@"onclick=.+?""","onclick=");
                            pageButton.Remark = "收集页面命令";
                            var flg = _menuElementService.Exists(p => p.Name == pageButton.Name && p.ModuleId == menu.ID);
                            if(!flg) {
                                _menuElementService.Add(pageButton);
                            }
                        }
                    }
                }
            }
            return Success("收集页面命令成功。");
        }
        private static string GetBtnInfo(string m_outstr,string pattern,string filter = "") {
            string tempstr = "";
            Regex s = new Regex(pattern);
            if(s.IsMatch(m_outstr)) {
                foreach(Match item in s.Matches(m_outstr)) {
                    tempstr = item.Groups[0].Value;
                    tempstr = tempstr.Replace(@"""","");
                    tempstr = tempstr.Replace(filter,"");
                    break;
                }
            }
            return tempstr;
        }
        private string GetPageContent(string url) {
            try {
                //登录 /Login/index?sinOut=true
                var client = new WebClientHelper();
                client.BaseAddress = baseUrl;
                string srcString = client.PostData("/Login/CheckLogin","username=admin&password=admin&code=admin");
                string pageHtml = client.DownloadString(url);
                return getFirstNchar(pageHtml);
            } catch(Exception ex) {
                Logger.LogError("WebClient:" + url,ex);
                return string.Empty;
            }
        }
        private string getFirstNchar(string instr) {
            string m_outstr = instr.Clone() as string;
            m_outstr = new Regex(@"(?m)<script[^>]*>(\w|\W)*?</script[^>]*>",RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr,string.Empty);
            m_outstr = new Regex(@"(?m)<style[^>]*>(\w|\W)*?</style[^>]*>",RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr,string.Empty);
            m_outstr = new Regex(@"(?m)<link[^>]*>(\w|\W)*?[^>]*>",RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr,string.Empty);
            m_outstr = new Regex(@"<iframe[\s\S]+</iframe *>",RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr,string.Empty);
            m_outstr = new Regex(@"<frameset[\s\S]+</frameset  *>",RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr,string.Empty);
            m_outstr = new Regex(@"-->",RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr,string.Empty);
            m_outstr = new Regex(@"<!--.*",RegexOptions.Multiline | RegexOptions.IgnoreCase).Replace(m_outstr,string.Empty);
            m_outstr = new Regex(@"(&nbsp;)+").Replace(m_outstr,"");
            m_outstr = new Regex(@"(\r\n\r\n)+").Replace(m_outstr,"");
            return m_outstr;
        }
        [HttpPost]
        public override IActionResult Switch(string keyId) {
            _menuService.Switch(keyId);
            return Success("操作成功。");
        }
        public override IActionResult SubmitForm(Menu moduleEntity) {
            if(moduleEntity.ParentID == "0") moduleEntity.ParentID = Guid.Empty.ToString();
            moduleEntity.Icon = "fa fa-bars";
            return base.SubmitForm(moduleEntity);
        }
        public override IActionResult DeleteForm(string keyValue) {
            if(string.IsNullOrWhiteSpace(keyValue)) return Error("参数keyValue不能为空！");
            _menuService.DeleteAll(keyValue);
            return Success("删除成功。");
        }
    }
}